package com.epro.dx.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baifendian.mobile.BfdAgent;
import com.epro.dx.R;
import com.epro.dx.activity.DetailActivity;
import com.epro.dx.activity.HomeActivity;
import com.epro.dx.activity.LoginActivity;
import com.epro.dx.activity.order.OrderPlaceActivity;
import com.epro.dx.adapter.ProductListAdapter;
import com.epro.dx.adapter.ShoppingCartAdapter;
import com.epro.dx.adapter.ShoppingCartAdapter.FavoriteBtnListenner;
import com.epro.dx.adapter.ShoppingCartAdapter.OnProductChangeListenner;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.listenner.OnLoginSuccessedListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.task.GetProductsFromSkusAsyncTask;
import com.epro.dx.task.GetRecommendTask;
import com.epro.dx.task.GetRecommendTask.GetRecommendsModel;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.ClickUtils;
import com.epro.dx.util.DpPxUtils;
import com.epro.dx.util.GlobalConfig;
import com.epro.dx.util.LoginUtilTask;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.epro.dx.widget.BottomBtn;
import com.epro.dx.widget.MyGridView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.ecommerce.Product;
import com.google.android.gms.analytics.ecommerce.ProductAction;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.constants.ServerConstant.ReturnCode.User;
import com.weipu.common.facade.content.api.MyCartService;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.Lines;
import com.weipu.common.facade.model.OrderProductModel;
import com.weipu.common.facade.model.OrderProductModel.SalesLimit;
import com.weipu.common.facade.model.PreviewOrderModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;
import com.weipu.common.util.NetWorkUtil;
import com.weipu.common.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车
 *
 * @author hjd008
 * @version [版本号, 2015-1-6]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ShoppingCartFragment extends BaseFragment implements
        OnClickListener, OnItemClickListener, OnItemLongClickListener,
        FavoriteBtnListenner, OnProductChangeListenner,
        OnRefreshListener<ListView> {
    /**
     * 日志tag
     */
    private static final String TAG = "ShoppingCartFragment";

    private static final long CACHA_TIEM = 10 * 1000;

    /**
     * 父布局
     */
    private View rootView;

    /**
     * 空布局
     */
    private ScrollView emptyLayout;

    /**
     * START SHOPPING 按钮
     */
    private Button btnStartShopping;

    /**
     * 主布局
     */
    private RelativeLayout contentLayout;

    /**
     * 底部总价格
     */
    private TextView totalPrice;
    /**
     * 底部总折扣价格
     */
    private TextView discount;

    /**
     * checkout
     */
    private Button btnCheckOut;

    /**
     * 购物车商品列表
     */
    // private ListView listView;
    private PullToRefreshListView listView;

    /**
     * 购物车商品列表适配器
     */
    private ShoppingCartAdapter shoppingCartAdapter;

    private MyCartService mycartservice = ProviderFactory
            .createMyCartServiceDBProvider();

    /**
     * 与adapter绑定的 数据
     */
    private ArrayList<OrderProductModel> localeCartList;

    /**
     * 客户端本地数据库中购物车对象列表
     */
    private ArrayList<OrderProductModel> orderProductModelresults = new ArrayList<OrderProductModel>();

    /**
     * saleLimit的数据存储
     */
    private Map<Integer, Integer> limitMap = new HashMap<Integer, Integer>();

    private boolean isPriceChange;

    private boolean isHidden = true;

    // 用于存储本地查询所得的ID
    private Map<Integer, Integer> IDs = new HashMap<Integer, Integer>();
    // 连接服务器获取的数据对象
    private PreviewOrderModel previewOrderModel;

    private boolean isClearCart;

    // 网络错误页面
    private LinearLayout netErroLayout;
    // 重试按钮
    private Button tryAgain;

    // 数据为空的时候的推荐商品列表
    private MyGridView bfdProductList;

    private LinearLayout bfdProductsLayout;
    private LinearLayout emptyLayoutTop;

    private ProductListAdapter productListAdapter;
    private List<ProductModel> myBfdProducts = new ArrayList<ProductModel>();

    private TextView scTipTv;

    private View sddiv;

    private RelativeLayout endPriceParent;

    private CheckBox cbAll;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflate(R.layout.fragment_shoppingcart);
            initView();
        }
        ActivityUtil.setStatusColor(getActivity(), 0, rootView);
        return rootView;
    }

    private void excuteTask(boolean isPullDown) {
        // 判断是否登陆，加入线上同步逻辑
        if (ActivityUtil.isLogin(getActivity())) {// 已经登陆走线上同步逻辑
            AsyncTaskUtil.executeTask(new GetOnlineShoppingCart(isPullDown));
        } else {// 没有登陆走本地逻辑
            previewOrderModel = null;
            AsyncTaskUtil.executeTask(new GetLocalDataAsyncTask(isPullDown));
        }
    }

    protected int getDensityDpi() {
        DisplayMetrics metrics = new DisplayMetrics();
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        display.getMetrics(metrics);
        return metrics.densityDpi;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHidden = hidden;
        if (!hidden) {
            excuteTask(false);
        } else {
            if (loadingLayout != null
                    && loadingLayout.getVisibility() == View.VISIBLE) {
                loadingLayout.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onResume() {
        // if (!isHidden) {
        if (BottomBtn.SHOPPING_TAG == ((HomeActivity) getActivity()).mIndicator
                .getCurrentTab()) {
            excuteTask(false);
        }
        // 百分点推荐
        BfdAgent.setDebugMode(Constant.BFD_DEBUGMODEL);
        BfdAgent.onResume(getActivity());
        super.onResume();
    }

    @Override
    public void onPause() {
        BfdAgent.onPause(getActivity());
        super.onPause();
    }

    private void initView() {

        Log.i(this.getClass().getSimpleName(), "----------onResume------------");
        // 设置标题
        setTitleContent(R.string.title_shopping_cart);
        emptyLayout = (ScrollView) rootView
                .findViewById(R.id.shoppingcart_layout_empty);
        emptyLayoutTop = (LinearLayout) rootView
                .findViewById(R.id.empty_layout_top);
        btnStartShopping = (Button) rootView
                .findViewById(R.id.btn_start_shopping);
        contentLayout = (RelativeLayout) rootView
                .findViewById(R.id.shoppingcart_layout_content);
        listView = (PullToRefreshListView) rootView
                .findViewById(R.id.shoppingcart_listview);
        // 底部总价布局
        totalPrice = (TextView) rootView
                .findViewById(R.id.tv_shoppingcart_totalprice);
        // 底部折扣总额布局
        discount = (TextView) rootView
                .findViewById(R.id.tv_shoppingcart_discount);
        btnCheckOut = (Button) rootView.findViewById(R.id.btn_checkout);
        // 网络错误页面
        // netErroLayout = (LinearLayout) rootView
        // .findViewById(R.id.shoppingcart_layout_neterro);

        // 空页面推荐商品 列表
        bfdProductList = (MyGridView) rootView
                .findViewById(R.id.bfd_product_list);
        bfdProductsLayout = (LinearLayout) rootView
                .findViewById(R.id.bfd_shoppingcart);
        tryAgain = (Button) rootView.findViewById(R.id.try_again);
        tryAgain.setOnClickListener(this);
        btnStartShopping.setOnClickListener(this);
        listView.setMode(Mode.PULL_FROM_START);
        listView.setOnRefreshListener(this);
        listView.setOnItemClickListener(this);
        listView.getRefreshableView().setOnItemLongClickListener(this);
        btnCheckOut.setOnClickListener(this);
        localeCartList = new ArrayList<OrderProductModel>();
        shoppingCartAdapter = new ShoppingCartAdapter(getActivity(), this,
                orderProductModelresults, true, getDensityDpi(),
                NetWorkUtil.isWifi(getActivity()));
        shoppingCartAdapter.setFavoriteListenner(this);
        listView.setAdapter(shoppingCartAdapter);

        productListAdapter = new ProductListAdapter(getActivity(),
                myBfdProducts, false, getDensityDpi(),
                ((HomeActivity) getActivity()).tracker);
        bfdProductList.setAdapter(productListAdapter);
        scTipTv = (TextView) rootView.findViewById(R.id.tv_shoppingcart_sc);
        sddiv = rootView.findViewById(R.id.tv_shoppingcart_scdiv);
        endPriceParent = (RelativeLayout) rootView.findViewById(R.id.endprice_layout);

        cbAll = (CheckBox) rootView.findViewById(R.id.cb_shoppingcart_all);
        cbAll.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isChecked = cbAll.isChecked();
                shoppingCartAdapter.check(isChecked);
                excuteTask(false);
            }
        });

    }

    public void synchronizeCheck(boolean isAll) {
        cbAll.setChecked(isAll);
    }

    public void updateSelected(OrderProductModel productModel) {
        if (ActivityUtil.isLogin(getActivity())/* &&isClearCart */) {
            AsyncTaskUtil.executeTask(new UpdateItemLogin(true, productModel.getSku(), false));
        } else {
            updateItem(productModel, false);
        }
    }

    /**
     * @author Tony 校验库存
     */
    class CheckStock extends BaseNeedReLoginTask {

        private PreviewOrderModel previewOrder;

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(null);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... arg0) {
            if (orderProductModelresults != null
                    && orderProductModelresults.size() > 0) {
                ArrayList<Lines> lines = new ArrayList<Lines>();
                for (int i = 0; i < orderProductModelresults.size(); i++) {
                    OrderProductModel model = orderProductModelresults.get(i);
                    Lines line = new Lines();
                    line.setSku(model.getSku());
                    line.setQty(model.getQuantity());
                    line.setSellingPrice(model.getPrice());
                    lines.add(line);
                }
                try {
                    List<Integer> notSelectedSkus = shoppingCartAdapter.getNotSelectedSkus();
                    previewOrder = ProviderFactory
                            .createCouponServiceProvider().PreviewOrder(
                                    (int) getCustomerID(), null, 0, lines,
                                    null, "USD",
                                    ActivityUtil.getCustomerToken(), notSelectedSkus);
                } catch (DxException e) {
                    return e.getErrCode();
                }
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
//			hideWaitingDialog();
            hideLoadingLayout();
            ArrayList<OrderProductModel> results = new ArrayList<OrderProductModel>();

            if ("0".equals(result)) {
                if (previewOrder != null && previewOrder.getLines() != null) {
                    orderProductModelresults.clear();
                    orderProductModelresults.addAll(previewOrder.getLines());

                    for (OrderProductModel orderProductModel : previewOrder.getLines()) {
                        if (shoppingCartAdapter.getCheck(orderProductModel.getSku())) {
                            results.add(orderProductModel);
                        }
                    }
                }

                if (results.isEmpty()) {
                    AlertToast.alert(getActivity(), R.string.goods_sold_out);
                }

                if (checkLimit()) {
                    // 判断是否登录
                    if (ActivityUtil.isLogin(getActivity())) {
                        isClearCart = true;
                        if (isPriceChange) {
                            isPriceChange = false;
                            AlertToast.alert(getActivity(),
                                    R.string.goods_price_change);
                            return;
                        }
                        submitOrder(previewOrder,results);

                    } else {
                        isClearCart = false;
                        Intent intent = new Intent(getActivity(),
                                LoginActivity.class);
                        // intent.putParcelableArrayListExtra(
                        // ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP,
                        // orderProductModelresults);
                        intent.putExtra(
                                ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                                ServerConstant.Parameter.PARAMETER_ACTION_TYPE_MYCART);
                        // 登陆成功后直接跳转到checkout页面所需要的数据
                        intent.putParcelableArrayListExtra(
                                ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP,
                                results);
                        intent.putExtra("isClearCart", isClearCart);
                        if (previewOrderModel != null) {
                            if (!TextUtils.isEmpty(previewOrderModel
                                    .getCurrencyCodeStr())) {
                                intent.putExtra(
                                        ServerConstant.Parameters.PARAMETERS_CURRENCYCODESTR,
                                        previewOrder.getCurrencyCodeStr());
                            }
                            intent.putExtra(
                                    ServerConstant.Parameters.PARAMETERS_DISCOUNT,
                                    previewOrder.getAllDiscountTotal());
                            intent.putExtra(
                                    ServerConstant.Parameters.PARAMETERS_GRANDTOTAL,
                                    previewOrder.getGrandTotal());
                            intent.putExtra(
                                    ServerConstant.Parameters.PARAMETERS_SUBTOTAL,
                                    previewOrder.getGoodsTotal());
                            intent.putExtra(
                                    ServerConstant.Parameters.PARAMETERS_RETURNSC,
                                    previewOrder.getExpectReturnSCAmount());

                        }
                        startActivity(intent);
                    }
                } else {
                    AlertToast.alert(getActivity(), R.string.goods_sold_out);
                }
            } else if (!isRelogin) {
                //加载失败
                AlertToast.alert(getActivity(), ServerConstant.ReturnCode.MESSAGEMAP.get(result));
            }
            super.onPostExecute(result);
        }

        @Override
        protected Context setContext() {
            return getActivity();
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new CheckStock();
        }
    }

    /**
     * 获取本地数据库购物车数据
     *
     * @author hjd008
     * @version [版本号, 2014-12-26]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    class GetLocalDataAsyncTask extends BaseNeedReLoginTask {

        private ArrayList<OrderProductModel> selectMenusList;

        private boolean isPullDown;

        public GetLocalDataAsyncTask(boolean isPullDown) {
            this.isPullDown = isPullDown;
        }

        @Override
        protected void onPreExecute() {
            if (!isPullDown) {
                showLoadingLayout(null);
            }
            emptyLayout.setVisibility(View.GONE);
            // showWaitingDialog();
            GlobalConfig.getInstance().setShoppingCartChange(false);
            isPriceChange = false;

        }

        @Override
        protected String doInBackground(Void... params) {
            selectMenusList = getLocalList();
            if (null != selectMenusList && selectMenusList.size() > 0) {
                ArrayList<Lines> lines = new ArrayList<Lines>();
                for (int i = 0; i < selectMenusList.size(); i++) {
                    OrderProductModel model = selectMenusList.get(i);
                    Lines line = new Lines();
                    line.setSku(model.getSku());
                    line.setQty(model.getQuantity());
                    line.setSellingPrice(model.getPrice());
                    lines.add(line);
                }
                // 调用预览订单接口
                String currencyCode = StringUtil.getConfig(
                        ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE,
                        "USD");
                try {

                    List<Integer> notSelectedSkus = shoppingCartAdapter.getNotSelectedSkus();
                    previewOrderModel = ProviderFactory
                            .createCouponServiceProvider().PreviewOrder(
                                    (int) getCustomerID(), null, 0, lines,
                                    null, currencyCode,
                                    ActivityUtil.getCustomerToken(), notSelectedSkus);
                } catch (DxException e) {
                    return e.getErrCode();
                }

            } else {
                return "1";
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
//			hideWaitingDialog();
//			hideLoadingLayout();
            showContentLayout(null);
            listView.onRefreshComplete();
            if ("0".equals(result) && previewOrderModel != null
                    && previewOrderModel.getLines() != null) {
                orderProductModelresults.clear();
                List<OrderProductModel> lines = previewOrderModel.getLines();
                if (null != lines) {
                    orderProductModelresults.addAll(lines);
                }
                shoppingCartAdapter.setCurrencyCode(
                        previewOrderModel.getCurrencyCode(),
                        previewOrderModel.getCurrencyCodeStr());
                setData2View();
            } else if ("1".equals(result)) {
                // 本地没有数据
                orderProductModelresults.clear();
                setData2View();
            } else if (!isRelogin) {
                if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE
                        .equals(result)) {
                    showErrorNetLayout(contentLayout);
                    // netErroLayout.setVisibility(View.VISIBLE);
                    emptyLayout.setVisibility(View.GONE);
                    // contentLayout.setVisibility(View.GONE);
                } else {
                    showErrorNetLayout(contentLayout, R.string.server_busy,
                            R.string.server_suggest);
                }
                // 显示网络异常页面
                // netErroLayout.setVisibility(View.VISIBLE);
                emptyLayout.setVisibility(View.GONE);
                // contentLayout.setVisibility(View.GONE);
            }

        }

        @Override
        protected Context setContext() {
            return getActivity();
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new GetLocalDataAsyncTask(isPullDown);
        }

    }

    /**
     * @author Tony 获取线上同步购物车数据的任务
     */
    class GetOnlineShoppingCart extends AsyncTask<Void, Void, String> {

        private int successDelLocalData = -1;
        private ArrayList<OrderProductModel> localCartDatas;
        private ArrayList<Lines> skus;
        private boolean isPullDown;

        public GetOnlineShoppingCart(boolean isPullDown) {
            this.isPullDown = isPullDown;
        }

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            if (!isPullDown) {
                showLoadingLayout(null);
            }
            emptyLayout.setVisibility(View.GONE);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                localCartDatas = mycartservice.selectMenusList(getActivity(),
                        "_id desc");
                if (localCartDatas != null && localCartDatas.size() > 0) {
                    // 将本地数据同步到服务器并清除本地数据
                    successDelLocalData = 0;
                    skus = new ArrayList<Lines>();
                    for (int i = 0; i < localCartDatas.size(); i++) {
                        Lines lines = new Lines();
                        OrderProductModel model = localCartDatas.get(i);
                        lines.setSku(model.getSku());
                        lines.setQty(model.getQuantity());
                        lines.setSellingPrice(model.getPrice());
                        skus.add(lines);
                    }
                    previewOrderModel = ProviderFactory
                            .createShoppingCartServiceProvider()
                            .uploadLocalCart(skus, getCustomerID(),
                                    ActivityUtil.getCustomerToken());

                    successDelLocalData = 1;
                    // 清除数据
                    for (int i = 0; i < localCartDatas.size(); i++) {
                        OrderProductModel model = localCartDatas.get(i);
                        mycartservice.deleteById(getActivity(), model.getId());
                    }
                    successDelLocalData = 2;

                } else {
                    String notSelectedSkuStr = shoppingCartAdapter.getNotSelectedSkuStr();
                    previewOrderModel = ProviderFactory
                            .createShoppingCartServiceProvider().getCart(
                                    getCustomerID(),
                                    ActivityUtil.getCustomerToken(), notSelectedSkuStr);
                }
                StringUtil.saveConfig("IsUploadSucc", "true");
                if (previewOrderModel == null) {
                    return "0";
                }


            } catch (DxException e) {
                return e.getErrCode();
            }

            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if ("0".equals(result)) {
                // hideWaitingDialog();
                listView.onRefreshComplete();
                showContentLayout(null);
                if (previewOrderModel != null) {
                    if (!previewOrderModel.isMerged()) {
                        AlertToast.alert(getActivity(), R.string.sku_conflict);
                    }
                    orderProductModelresults.clear();
                    List<OrderProductModel> lines = previewOrderModel
                            .getLines();
                    if (null != lines) {
                        orderProductModelresults.addAll(lines);
                    }
                    shoppingCartAdapter.setCurrencyCode(
                            previewOrderModel.getCurrencyCode(),
                            previewOrderModel.getCurrencyCodeStr());
                    // isClearCart = true;
                } else {
                    orderProductModelresults.clear();
                    // isClearCart = false;
                }
                // 刷新小红点数量显示
                HomeActivity homeactivity = (HomeActivity) getActivity();
                if (null != homeactivity) {
                    homeactivity.getAndSetCount();
                }
                setData2View();
            } else {
                // isClearCart = false;
                // 登录失效
                if ("DMS100002".equals(result)) {
                    LoginUtilTask logintask = new LoginUtilTask(
                            new OnLoginSuccessedListenner() {

                                @Override
                                public void onLoginSuccesed() {
                                    AsyncTaskUtil.executeTask(new GetOnlineShoppingCart(
                                            false));

                                }

                                @Override
                                public void onLoginFailed() {
                                    autoLoginFailToLogin(true);
                                }
                            }, getActivity(), true);
                    AsyncTaskUtil.executeTask(logintask);
                } else if ("DMS100005".equals(result)) {
                    orderProductModelresults.clear();
                    //同步时错误码DMS100005 表示有且只有无库存产品进行同步时出现， 清除数据
                    for (int i = 0; i < localCartDatas.size(); i++) {
                        OrderProductModel model = localCartDatas.get(i);
                        mycartservice.deleteById(getActivity(), model.getId());
                    }
                    //同步失败后读取个人购物车的数据
                    AsyncTaskUtil.executeTask(new GetCustomerShoppingCart());
                } else {
                    //代表同步失败的情况下
                    if (successDelLocalData == 0) {
                        AsyncTaskUtil.executeTask(new GetCustomerShoppingCart());
                    } else {
                        hideLoadingLayout();
                        listView.onRefreshComplete();
                        if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE
                                .equals(result)) {
                            showErrorNetLayout(contentLayout);
                            emptyLayout.setVisibility(View.GONE);
                        } else {
                            showErrorNetLayout(contentLayout, R.string.server_busy,
                                    R.string.server_suggest);
                        }
                    }

                }

            }
            super.onPostExecute(result);
        }

    }

    /**
     * @author 获取用户
     */
    class GetCustomerShoppingCart extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {

                previewOrderModel = ProviderFactory
                        .createShoppingCartServiceProvider().getCart(
                                getCustomerID(),
                                ActivityUtil.getCustomerToken(), "");
            } catch (DxException e) {
                return e.getErrCode();
            }

            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if ("0".equals(result)) {
                listView.onRefreshComplete();
                showContentLayout(null);
                if (previewOrderModel != null) {
                    orderProductModelresults.clear();
                    List<OrderProductModel> lines = previewOrderModel
                            .getLines();
                    if (null != lines) {
                        orderProductModelresults.addAll(lines);
                    }
                    shoppingCartAdapter.setCurrencyCode(
                            previewOrderModel.getCurrencyCode(),
                            previewOrderModel.getCurrencyCodeStr());
                    // isClearCart = true;
                } else {
                    orderProductModelresults.clear();
                    // isClearCart = false;
                }
                // 刷新小红点数量显示
                HomeActivity homeactivity = (HomeActivity) getActivity();
                if (null != homeactivity) {
                    homeactivity.getAndSetCount();
                }
                setData2View();
            } else {
                hideLoadingLayout();
                listView.onRefreshComplete();
                if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE
                        .equals(result)) {
                    showErrorNetLayout(contentLayout);
                    emptyLayout.setVisibility(View.GONE);
                } else {
                    showErrorNetLayout(contentLayout, R.string.server_busy,
                            R.string.server_suggest);
                }
            }

            super.onPostExecute(result);
        }

    }

    /**
     * 获取CustomerID
     *
     * @return CustomerID
     */
    public long getCustomerID() {
        // 获取CustomerId
        String customerid = com.weipu.common.util.GlobalConfig.getInstance()
                .getUserSessionCfg().getCustomerid();
        if (null == customerid || "".equals(customerid)) {
            customerid = StringUtil.getConfig(
                    ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID, "0");
        }
        return Long.parseLong(customerid);
    }

    /**
     * 更新页面数据
     *
     * @see [类、类#方法、类#成员]
     */
    public void setData2View() {
        // 当前购车对象列表为空，终止其它模块加载
        if (null == orderProductModelresults
                || orderProductModelresults.size() == 0) {
            shoppingCartAdapter.notifyDataSetChanged();
            emptyLayout.setVisibility(View.VISIBLE);
            contentLayout.setVisibility(View.GONE);
            // 购物车没有数据，显示百分点推荐栏
            emptyLayout.scrollTo(0, 0);
            getRecommendProducts();
        } else {
            if (ActivityUtil.isLogin(getActivity())) {
                String name = StringUtil.getConfig(getActivity(),
                        ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
                for (int i = 0; i < orderProductModelresults.size(); i++) {
                    OrderProductModel opModel = orderProductModelresults.get(i);
                    if (null != name
                            && name.equals(StringUtil.getConfig(getActivity(),
                            opModel.getSku() + ""))) {
                        opModel.setIsFavorite("true");
                    }
                }
            }
            emptyLayout.setVisibility(View.GONE);
            contentLayout.setVisibility(View.VISIBLE);
            shoppingCartAdapter.update();
            // --------------------显示金额信息-----------------------------
            if (previewOrderModel == null) {
                return;
            }
            double discountTotal = previewOrderModel.getAllDiscountTotal();
            if (discountTotal > 0) {
                // 有优惠，显示优惠价格信息
                discount.setVisibility(View.VISIBLE);
                discount.setText(getActivity().getString(
                        R.string.product_discount_price,
                        "-" + previewOrderModel.getCurrencyCodeStr()
                                + String.format("%.2f", discountTotal)));
            } else {
                // 没有优惠，不显示优惠价格信息
                discount.setVisibility(View.GONE);
            }
            // String price= previewOrderModel.getGrandTotal()+"";

            // totalPrice.setText(getActivity().getString(
            // R.string.product_total_price,
            // previewOrderModel.getCurrencyCodeStr()
            // + previewOrderModel.getGrandTotal()));
            double grandTotal = previewOrderModel.getGrandTotal();
            String total = "";
            if (grandTotal >= 0) {
                total = String.format("%.2f", grandTotal);
            }
            totalPrice.setText(Html.fromHtml(getActivity().getString(
                    R.string.cart_total_price)
                    + "<font color='#fd8917'>"
                    + previewOrderModel.getCurrencyCodeStr()
                    + total
                    + "</font>"));

            float sc = previewOrderModel.getExpectReturnSCAmount();

            showScText(previewOrderModel.getCurrencyCodeStr(), sc);
        }
    }

    private void showScText(String codeStr, float sc) {
        if (sc <= 0f) {
            scTipTv.setVisibility(View.GONE);
            sddiv.setVisibility(View.GONE);
            LayoutParams lp = endPriceParent.getLayoutParams();
            lp.height = DpPxUtils.Dp2Px(getActivity(), 45);
            endPriceParent.setLayoutParams(lp);
            return;
        }

        LayoutParams lp = endPriceParent.getLayoutParams();
        lp.height = DpPxUtils.Dp2Px(getActivity(), 65);
        endPriceParent.setLayoutParams(lp);

        scTipTv.setVisibility(View.VISIBLE);
        sddiv.setVisibility(View.VISIBLE);

        String boldString = codeStr + sc;
        String scString = getString(R.string.sc_tip, boldString);
        int start = scString.lastIndexOf(boldString);
        int end = start + boldString.length();
        SpannableStringBuilder style = new SpannableStringBuilder(scString);
        style.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        scTipTv.setText(style);
    }

    @Override
    public void onClick(View view) {
        if (ClickUtils.isFastDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_start_shopping:
                // 跳转browse tab
                ((HomeActivity) getActivity())
                        .setCurrentTabByTag(getString(HomeActivity.titleArray[0]));
                break;
            // 对选中购物车下单
            case R.id.btn_checkout:
                if (!shoppingCartAdapter.isCheckOne()) {
                    AlertToast.alert(getActivity(), R.string.goods_not_selected);
                    return;
                }
                // 首先判断库存
                if (checkLimit()) {
                    AsyncTaskUtil.executeTask(new CheckStock());
                } else {
                    AlertToast.alert(getActivity(), R.string.goods_sold_out);
                }
                break;
            case R.id.try_again:
                excuteTask(false);
                break;
            default:
                break;
        }
    }

    /**
     * 检查库存判断是否可以checkout
     *
     * @return 是否没有库存问题
     * @see [类、类#方法、类#成员]
     */
    private boolean checkLimit() {
        limitMap.clear();
        if (null == orderProductModelresults) {
            return false;
        }
        for (int i = 0; i < orderProductModelresults.size(); i++) {
            OrderProductModel productModel = orderProductModelresults.get(i);
            SalesLimit salesLimit = productModel.getSalesLimit();
            if (salesLimit != null && salesLimit.getDistributionPolicy() == 0) {
                limitMap.put(productModel.getSku(), 0);
            }
        }
        if (limitMap.size() > 0) {
            return false;
        }
        return true;
    }

    /**
     * 下单
     *
     * @see [类、类#方法、类#成员]
     */
    private void submitOrder(PreviewOrderModel previewOrder,ArrayList<OrderProductModel> results) {
        if (null != orderProductModelresults
                && !orderProductModelresults.isEmpty()) {
            measureCheckOut();
            Intent intent = new Intent(getActivity(), OrderPlaceActivity.class);
            GlobalConfig.getInstance().setShoppingCartChange(true);
            // // 传递一个标识，表示从mycartActivity付款的，此时付款完成后需要删除购物车的商品
            // intent.putExtra(
            // ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
            // ServerConstant.ActionConstant.FORM_MYCART_ACTIVITY);
            intent.putParcelableArrayListExtra(
                    ServerConstant.Parameter.PARAMETER_NAME_ORDER_ORDERMAP,
                    results);
            intent.putExtra("isClearCart", isClearCart);
            if (previewOrderModel != null) {
                if (!TextUtils.isEmpty(previewOrderModel.getCurrencyCodeStr())) {
                    intent.putExtra(
                            ServerConstant.Parameters.PARAMETERS_CURRENCYCODESTR,
                            previewOrder.getCurrencyCodeStr());
                }
                intent.putExtra(ServerConstant.Parameters.PARAMETERS_DISCOUNT,
                        previewOrder.getAllDiscountTotal());
                intent.putExtra(
                        ServerConstant.Parameters.PARAMETERS_GRANDTOTAL,
                        previewOrder.getGrandTotal());
                intent.putExtra(ServerConstant.Parameters.PARAMETERS_SUBTOTAL,
                        previewOrder.getGoodsTotal());
                intent.putExtra(ServerConstant.Parameters.PARAMETERS_RETURNSC,
                        previewOrder.getExpectReturnSCAmount());

            }
            startActivity(intent);
        }

    }

    /**
     * 衡量checkout操作
     *
     * @see [类、类#方法、类#成员]
     */
    private void measureCheckOut() {
        Logger.d("measureCheckOut start");
        ProductAction productAction = new ProductAction(
                ProductAction.ACTION_CLICK).setProductActionList("Add To Cart");
        HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder();
        builder.setProductAction(productAction);
        for (int i = 0; i < localeCartList.size(); i++) {
            OrderProductModel model = localeCartList.get(i);
            Product product = new Product()
                    .setId(String.valueOf(model.getSku()))
                    .setName(model.getShortHeadLine1())
                    .setQuantity(model.getQuantity())
                    .setPrice(model.getPrice());
            builder.addProduct(product);
        }
        Tracker t = DXApplication.getContext().getTracker(
                TrackerName.APP_TRACKER);
        // t.setScreenName(ShoppingCartFragment.class.getSimpleName());
        t.send(builder.build());
        Logger.d("measureCheckOut end");
    }

    /**
     * 更新一个购物车商品
     *
     * @param productModel
     * @see [类、类#方法、类#成员]
     */
    public void updateItem(OrderProductModel productModel, boolean isLimitChange) {
        Logger.i("TAG---", "---updateItem ---");
        new UpdateItem(isLimitChange).execute(productModel);
    }

    /**
     * 获取本地数据库信息
     *
     * @return
     */
    public ArrayList<OrderProductModel> getLocalList() {
        ArrayList<OrderProductModel> selectMenusList = mycartservice
                .selectMenusList(getActivity(), "_id desc");
        if (selectMenusList != null && selectMenusList.size() > 0) {
            for (int i = 0; i < selectMenusList.size(); i++) {
                OrderProductModel model = selectMenusList.get(i);
                IDs.put(model.getSku(), model.getId());
            }
        }
        return selectMenusList;
    }

    private class UpdateItemLogin extends AsyncTask<Void, Void, String> {
        private boolean isAdd;
        private int sku;
        private boolean isSelected = true;

        public UpdateItemLogin(boolean isAdd, int sku, boolean isSelected) {
            this.isAdd = isAdd;
            this.isSelected = isSelected;
            this.sku = sku;
        }

        public UpdateItemLogin(boolean isAdd, int sku) {
            this.isAdd = isAdd;
            this.sku = sku;
        }

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(null);
            emptyLayout.setVisibility(View.GONE);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                int num = 0;
                if (isAdd) {
                    num = 1;
                } else {
                    num = -1;
                }
                if (!isSelected) {
                    num = 0;
                }

                String notSelectedSkuStr = shoppingCartAdapter.getNotSelectedSkuStr();

                previewOrderModel = ProviderFactory
                        .createShoppingCartServiceProvider().addCart(sku, num,
                                getCustomerID(),
                                ActivityUtil.getCustomerToken(), notSelectedSkuStr);
            } catch (DxException e) {
                return e.getErrCode();
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if ("0".equals(result)) {
                // hideWaitingDialog();
                hideLoadingLayout();
                if (previewOrderModel != null) {
                    orderProductModelresults.clear();
                    List<OrderProductModel> lines = previewOrderModel
                            .getLines();
                    if (null != lines) {
                        orderProductModelresults.addAll(lines);
                    }
                } else {
                    orderProductModelresults.clear();
                }
                setData2View();
            } else {// 登录失效
                if ("DMS100002".equals(result)) {
                    LoginUtilTask logintask = new LoginUtilTask(
                            new OnLoginSuccessedListenner() {

                                @Override
                                public void onLoginSuccesed() {
                                    AsyncTaskUtil.executeTask(new UpdateItemLogin(
                                            isAdd, sku));
                                }

                                @Override
                                public void onLoginFailed() {
                                    autoLoginFailToLogin(false);
                                }
                            }, getActivity(), true);
                    AsyncTaskUtil.executeTask(logintask);
                } else {
                    // hideWaitingDialog();
                    // AlertToast.alert(getActivity(),
                    // ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                    showErrorNetLayout(contentLayout);
                    // netErroLayout.setVisibility(View.VISIBLE);
                    emptyLayout.setVisibility(View.GONE);
                    // contentLayout.setVisibility(View.GONE);
                }
                // orderProductModelresults.clear();
            }
            super.onPostExecute(result);
        }
    }

    /**
     * 更新购物车中订购数量
     *
     * @author hjd008
     * @version [版本号, 2015-1-12]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    private class UpdateItem extends AsyncTask<OrderProductModel, Void, String> {
        private boolean isLimitChange;

        public UpdateItem(boolean isLimitNum) {
            this.isLimitChange = isLimitNum;
        }

        @Override
        protected void onPreExecute() {
            if (!isLimitChange) {
                // showWaitingDialog();
                showLoadingLayout(null);
            }
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(OrderProductModel... params) {
            // 未登录，走本地逻辑
            if (IDs.containsKey(params[0].getSku())) {
                params[0].setId(IDs.get(params[0].getSku()));
            }
            mycartservice.update(getActivity(), params[0]);
            if (!isLimitChange) {
                // 查询数据库中商品信息并调用预览订单接口校验库存与计算金额信息
                ArrayList<OrderProductModel> localCartDatas = getLocalList();
                if (localCartDatas != null && localCartDatas.size() > 0) {
                    ArrayList<Lines> lines = new ArrayList<Lines>();
                    for (int i = 0; i < localCartDatas.size(); i++) {
                        OrderProductModel model = localCartDatas.get(i);
                        Lines line = new Lines();
                        line.setSku(model.getSku());
                        line.setQty(model.getQuantity());
                        line.setSellingPrice(model.getPrice());
                        lines.add(line);
                    }
                    String currencyCode = StringUtil
                            .getConfig(
                                    ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE,
                                    "USD");
                    try {

                        List<Integer> notSelectedSkus = shoppingCartAdapter.getNotSelectedSkus();
                        previewOrderModel = ProviderFactory
                                .createCouponServiceProvider().PreviewOrder(
                                        (int) getCustomerID(), null, 0, lines,
                                        null, currencyCode,
                                        ActivityUtil.getCustomerToken(), notSelectedSkus);
                    } catch (DxException e) {
                        return e.getErrCode();
                    }
                }

            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (!isLimitChange && isAdded()) {
                // hideWaitingDialog();
                hideLoadingLayout();
                if ("0".equals(result)) {
                    if (previewOrderModel != null) {
                        orderProductModelresults.clear();
                        // orderProductModelresults.addAll(previewOrderModel
                        // .getLines());
                        List<OrderProductModel> lines = previewOrderModel
                                .getLines();
                        if (null != lines) {
                            orderProductModelresults.addAll(lines);
                        }
                    }
                    setData2View();
                } else {
                    // AlertToast.alert(getActivity(),
                    // ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                    showErrorNetLayout(contentLayout);
                    // netErroLayout.setVisibility(View.VISIBLE);
                    emptyLayout.setVisibility(View.GONE);
                    // contentLayout.setVisibility(View.GONE);
                }
            }
            super.onPostExecute(result);
        }
    }

    /**
     * 根据当前选中购物车对象ID列表进行删除
     *
     * @author hjd008
     * @version [版本号, 2015-1-12]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    private class DeleteItem extends AsyncTask<Void, Void, String> {
        private OrderProductModel delModel;

        public DeleteItem(OrderProductModel model) {
            this.delModel = model;
        }

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(null);
            emptyLayout.setVisibility(View.GONE);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            if (ActivityUtil.isLogin(getActivity())/* &&isClearCart */) {// 已经登陆，走线上同步逻辑
                try {
                    String notSelectedSkuStr = shoppingCartAdapter.getNotSelectedSkuStr();
                    previewOrderModel = ProviderFactory
                            .createShoppingCartServiceProvider()
                            .removeSkuFromCart(delModel.getSku(),
                                    getCustomerID(),
                                    ActivityUtil.getCustomerToken(), notSelectedSkuStr);
                } catch (DxException e) {
                    return e.getErrCode();
                }
            } else {// 未登录，走本地逻辑
                if (IDs.containsKey(delModel.getSku())) {
                    delModel.setId(IDs.get(delModel.getSku()));
                }
                mycartservice.deleteById(getActivity(), delModel.getId());
                // 加载购物车数据列表
                ArrayList<OrderProductModel> localCartDatas = mycartservice
                        .selectMenusList(getActivity(), "_id desc");
                if (localCartDatas != null && localCartDatas.size() > 0) {
                    ArrayList<Lines> lines = new ArrayList<Lines>();
                    for (int i = 0; i < localCartDatas.size(); i++) {
                        OrderProductModel model = localCartDatas.get(i);
                        Lines line = new Lines();
                        line.setSku(model.getSku());
                        line.setQty(model.getQuantity());
                        line.setSellingPrice(model.getPrice());
                        lines.add(line);
                    }
                    String currencyCode = StringUtil
                            .getConfig(
                                    ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE,
                                    "USD");
                    try {
                        List<Integer> notSelectedSkus = shoppingCartAdapter.getNotSelectedSkus();
                        previewOrderModel = ProviderFactory
                                .createCouponServiceProvider().PreviewOrder(
                                        (int) getCustomerID(), null, 0, lines,
                                        null, currencyCode,
                                        ActivityUtil.getCustomerToken(), notSelectedSkus);
                    } catch (DxException e) {
                        return e.getErrCode();
                    }
                } else {
                    previewOrderModel = null;
                }
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (limitMap.containsKey(delModel.getSku())) {
                limitMap.remove(delModel.getSku());
            }
            if ("0".equals(result)) {
                // hideWaitingDialog();
                hideLoadingLayout();
                if (previewOrderModel != null) {
                    orderProductModelresults.clear();
                    // orderProductModelresults.addAll(previewOrderModel
                    // .getLines());
                    List<OrderProductModel> lines = previewOrderModel
                            .getLines();
                    if (null != lines) {
                        orderProductModelresults.addAll(lines);
                    }
                } else {
                    orderProductModelresults.clear();
                }
                setData2View();
                ((HomeActivity) getActivity()).setShoppingCartToast(-1);
                // 刷新小红点数量显示
                ((HomeActivity) getActivity()).getAndSetCount();
                // 百分点推荐
                BfdAgent.onRmCart(getActivity(), delModel.getSku() + "");

            } else {
                // 登录失效
                if ("DMS100002".equals(result)) {
                    LoginUtilTask logintask = new LoginUtilTask(
                            new OnLoginSuccessedListenner() {

                                @Override
                                public void onLoginSuccesed() {
                                    AsyncTaskUtil.executeTask(new DeleteItem(
                                            delModel));
                                }

                                @Override
                                public void onLoginFailed() {
                                    autoLoginFailToLogin(false);
                                }
                            }, getActivity(), true);
                    AsyncTaskUtil.executeTask(logintask);
                } else {
                    // hideWaitingDialog();
                    hideLoadingLayout();
                    AlertToast.alert(getActivity(),
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
            }
            super.onPostExecute(result);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        OrderProductModel cartItem = (OrderProductModel) shoppingCartAdapter
                .getItem(position - 1);// 由于换成下拉刷新的ListView 剪掉头部index

        Intent intent = new Intent(getActivity(), DetailActivity.class);
        Bundle data = new Bundle();

        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID,
                cartItem.getSku());

        data.putString(ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION,
                ServerConstant.ActionConstant.ACTION_MYCART);
        data.putString(ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
                ServerConstant.ActionConstant.ACTION_MYCART);

        intent.putExtras(data);
        startActivity(intent);

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
                                   int position, long id) {
        final OrderProductModel cartItem = (OrderProductModel) shoppingCartAdapter
                .getItem(position - 1);
        showDeleteDialog(cartItem);
        return true;
    }

    public ArrayList<OrderProductModel> getLocaleCartList() {
        return localeCartList;
    }

    public void showDeleteDialog(final OrderProductModel cartItem) {
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.delete)
                .setCancelable(true)
                .setMessage(R.string.user_wish_confirm_del)
                .setPositiveButton(R.string.btn_title_ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                new DeleteItem(cartItem).execute();
                            }
                        })
                .setNegativeButton(R.string.btn_title_cancel,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.cancel();
                            }
                        }).create().show();
    }

    /**
     * 添加到购物车任务
     *
     * @author hjd008
     * @version [版本号, 2014-12-23]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    protected class AddToWishListAsyncTask extends
            BaseNeedReLoginTask {

        private final int sku;

        private final String source;

        private final int position;
        String userName;

        public AddToWishListAsyncTask(int sku, String source, int position) {
            this.sku = sku;
            this.source = source;
            this.position = position;
        }

        @Override
        protected void onPreExecute() {
            // showWaitingDialog();
            showLoadingLayout(null);
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                userName = StringUtil.getConfig(getActivity(),
                        ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
                ProviderFactory.createUserServiceProvider().addWishlistForUser(
                        sku, source, ActivityUtil.getCustomerID(),
                        ActivityUtil.getCustomerToken());
            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("MyCartActivity", "AddToWishListAsyncTask", e);
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            // hideWaitingDialog();
            hideLoadingLayout();
            // isActionCompleted = true;
            if ("0".equals(result)) {
                AlertToast.alert(getActivity(),
                        R.string.user_collection_add_success);
                OrderProductModel opModel = orderProductModelresults
                        .get(position);
                opModel.setIsFavorite("true");
                StringUtil.saveConfig(opModel.getSku() + "", userName);
                shoppingCartAdapter.notifyDataSetChanged();
                // //更新本地数据
                // ProviderFactory
                // .createMyCartServiceDBProvider().update(getActivity(),
                // opModel);
            } else if (!isRelogin) {
                // 数据被用户清除后 用户点击已收藏的产品 将按钮标红
                if (User.WISHLIST_ADD_ERROR.equals(result)) {
                    OrderProductModel opModel = orderProductModelresults
                            .get(position);
                    opModel.setIsFavorite("true");
                    StringUtil.saveConfig(opModel.getSku() + "", userName);
                    shoppingCartAdapter.notifyDataSetChanged();
                }
                AlertToast.alert(getActivity(),
                        ServerConstant.ReturnCode.MESSAGEMAP.get(result));
            }
        }

        @Override
        protected Context setContext() {
            return getActivity();
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new AddToWishListAsyncTask(sku, source, position);
        }
    }

    private void gotoLogin() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        Bundle data = new Bundle();
        // 设置返回参数,登录成功后需要返回到详情界面
        data.putString(ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION,
                ServerConstant.ActionConstant.ACTION_PRODUCT_DETAIL);
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                ServerConstant.Parameter.PARAMETER_ACTION_TYPE_PRODUCT_DETAIL);
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID, 1);
        intent.putExtras(data);
        startActivity(intent);
    }

    /**
     * 点击添加到收藏夹
     *
     * @return void [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void addWishList(int sku, int position) {
        if (sku > 0) {
            // 如果未登录，则需要跳转到登录界面
            if (!ActivityUtil.isLogin(getActivity())) {
                gotoLogin();
                // isActionCompleted = true;
                return;
            }
            // new AddToWishListAsyncTask(sku, "",position).execute();
            AsyncTaskUtil.executeTask(new AddToWishListAsyncTask(sku, "",
                    position));
        }
        // 产品无效
        else {
            // isActionCompleted = true;
            AlertToast.alert(getActivity(), R.string.invalid_data);
        }

    }

    @Override
    public void favoriteBtnOnclick(int sku, int position) {
        addWishList(sku, position);
    }

    @Override
    public void deleteProductItem(OrderProductModel productModel) {
        showDeleteDialog(productModel);
    }

    @Override
    public void changeProductNum(OrderProductModel productModel, boolean isAdd,
                                 boolean isLimitChange) {
        if (ActivityUtil.isLogin(getActivity())/* &&isClearCart */) {
            if (!isLimitChange) {
                AsyncTaskUtil.executeTask(new UpdateItemLogin(isAdd,
                        productModel.getSku()));
            }
        } else {
            updateItem(productModel, isLimitChange);
        }

    }

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        excuteTask(true);
    }

    private void autoLoginFailToLogin(boolean isListComplete) {
        hideLoadingLayout();
        if (isListComplete) {
            listView.onRefreshComplete();
        }
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        intent.putExtra(
                ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                ServerConstant.Parameter.PARAMETER_ACTION_TYPE_AUTO_LOGIN_FAIL);
        getActivity().startActivity(intent);
    }

    /**
     * @创建：Tony 2016-5-13下午5:32:22
     * @描述：获取推荐商品
     */
    private void getRecommendProducts() {
        Map<String, String> params = new HashMap<String, String>();
        AsyncTaskUtil.executeTask(new GetRecommendTask(ActivityUtil.getCustomerID(), 2, new MyAsyncTaskListenner() {

            @Override
            public void onPreTask() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPostTask(String result, Object obj) {

//              Log.d(TAG, recommendRequestId + ">>" + json.toString());
                // 获取SKU列表，调用接口获取商品列表信息展示
                GetRecommendsModel model = (GetRecommendsModel) obj;
                //遗留问题 会报空指针异常
                if (model == null){
                    return;
                }
                if (model.IsSuccess && model.Skus != null) {
                    ArrayList<Integer> skus = new ArrayList<Integer>();
                    String[] splits = model.Skus.split(",");
                    for (int i = 0; i < splits.length; i++) {
                        skus.add(Integer.parseInt(splits[i]));
                    }
                    if (skus.size() > 0) {
                        AsyncTaskUtil
                                .executeTask(new GetProductsFromSkusAsyncTask(
                                        skus, getActivity(), 0, 60,
                                        Constant.SORT_POPULARITY,
                                        -2, OnekeyFilterLocalUtil.getFilterState(getActivity()), new MyAsyncTaskListenner() {

                                            @Override
                                            public void onPreTask() {

                                            }

                                            @SuppressWarnings("unchecked")
                                            @Override
                                            public void onPostTask(
                                                    String result,
                                                    Object bfdProducts) {
                                                if ("0".equals(result)
                                                        && bfdProducts != null
                                                        && ((ArrayList<ProductModel>) bfdProducts)
                                                        .size() > 0) {
                                                    // 显示推荐商品列表
                                                    bfdProductsLayout
                                                            .setVisibility(View.VISIBLE);
                                                    myBfdProducts
                                                            .clear();
                                                    myBfdProducts
                                                            .addAll(((ArrayList<ProductModel>) bfdProducts));
                                                    productListAdapter
                                                            .setCurrencyCode(
                                                                    ((ArrayList<ProductModel>) bfdProducts)
                                                                            .get(0)
                                                                            .getCurrencyCode(),
                                                                    ((ArrayList<ProductModel>) bfdProducts)
                                                                            .get(0)
                                                                            .getCurrencyCodeSymbol());
                                                    productListAdapter
                                                            .setRecommendRequestId("");
                                                    productListAdapter
                                                            .notifyDataSetChanged();
                                                } else {
                                                    // 隐藏推荐列表
                                                    if (null == myBfdProducts
                                                            || myBfdProducts
                                                            .size() <= 0) {
                                                        bfdProductsLayout
                                                                .setVisibility(View.GONE);
                                                    }
                                                }
                                            }
                                        }));
                    }
                }

            }
        }));
    }
}
